package com.bawan.ddbb.utils;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Desc:  ${TODO}
 * Author: zhengcongchun
 * CreateTime: 2014-06-11 11:34
 * LastModifyTime: 2014-06-11 11:34
 * FinalModifier: zhengcongchun
 * Version: 1.0
 */
public class IDGenatorUtil {

    private final BlockingQueue<String> idQueue;
    private static final int MAX_IDS = 100;
    private static final int MIN_IDS = 10;

    private static String idType = "MOBILE";

    private final ScheduledThreadPoolExecutor executor;

    private static class SingletonHolder {
        private static final SingletonHolder INSTANCE = new SingletonHolder();
    }

    public static SingletonHolder getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private IDGenatorUtil(BlockingQueue<String> idQueue){
        idType = SysCfg.get("id.generate.type", idType);
        this.idQueue = new LinkedBlockingQueue<String>();
        executor = new ScheduledThreadPoolExecutor(1);
        executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    productId();
                } catch (Exception e) {

                }
            }
        }, 0L, 10000L, TimeUnit.MILLISECONDS);
    }

    private void productId() throws InterruptedException {
        int size = idQueue.size();
        if (size < MIN_IDS) {
            while(true) {
                String seqId = getSequeuenceId();
                boolean success = idQueue.offer(seqId, 1000L, TimeUnit.MILLISECONDS);
                if (!success) break;
            }
        }
    }

    static String getSequeuenceId() {
        //TODO 生成ID规则
        return "";
    }
}
